package kr.hkit.powerjava.chapter18;

import javax.swing.JPanel;

import java.awt.BorderLayout;

import javax.swing.DefaultListModel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class PanelJListEx extends JPanel implements ListSelectionListener, ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel panel_Top;
	private JPanel panel_Center;
	private JPanel panel_Bottom;
	private JTextField textField;
	private JButton btnAdd;
	private JLabel lblNewLabel;
	private JTextField tfSelected;
	private JScrollPane scrollPane;
	private JList<String> list;

	/**
	 * Create the panel.
	 */
	public PanelJListEx() {

		initialize();
	}
	private void initialize() {
		setLayout(new BorderLayout(0, 0));
		
		panel_Top = new JPanel();
		add(panel_Top, BorderLayout.NORTH);
		
		textField = new JTextField();
		panel_Top.add(textField);
		textField.setColumns(10);
		
		btnAdd = new JButton("추가");
		btnAdd.addActionListener(this);
		panel_Top.add(btnAdd);
		
		panel_Center = new JPanel();
		add(panel_Center, BorderLayout.CENTER);
		
		list = new JList<String>();
		list.setModel(new DefaultListModel<String>());
		list.addListSelectionListener(this);
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scrollPane = new JScrollPane(list);
		panel_Center.add(scrollPane);
				
		panel_Bottom = new JPanel();
		add(panel_Bottom, BorderLayout.SOUTH);
		
		lblNewLabel = new JLabel("선택된 항목");
		panel_Bottom.add(lblNewLabel);
		
		tfSelected = new JTextField();
		tfSelected.setEditable(false);
		panel_Bottom.add(tfSelected);
		tfSelected.setColumns(10);
	}

	public void valueChanged(ListSelectionEvent e) {
		if (e.getSource() == list) {
			valueChangedList(e);
		}
	}
	
	protected void valueChangedList(ListSelectionEvent e) {
		tfSelected.setText(list.getSelectedValue());
	}
	
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnAdd) {
			actionPerformedBtnAdd(e);
		}
	}
	protected void actionPerformedBtnAdd(ActionEvent e) {
		DefaultListModel<String> model = (DefaultListModel<String>) list.getModel();
		String value = textField.getText().trim();
		
		model.addElement(value);
		
		textField.setText("");
		textField.requestFocus();
	}
}
